package com.css.fxfzfxqh.modules.buildingKilometerGrid.service;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzfxqh.common.rest.JcsjRestManager;
import com.css.fxfzfxqh.constants.GeomTypeEnum;
import com.css.fxfzfxqh.constants.YNEnum;
import com.css.fxfzfxqh.exceptions.ShpFieldException;
import com.css.fxfzfxqh.modules.buildingKilometerGrid.constant.FxqhBuildingGridTableTitleDesc;
import com.css.fxfzfxqh.modules.buildingKilometerGrid.exceptions.BizException;
import com.css.fxfzfxqh.modules.buildingKilometerGrid.model.entity.FxqhBuildingGridUrbanMasonry;
import com.css.fxfzfxqh.modules.buildingKilometerGrid.model.param.QueryByVersionParam;
import com.css.fxfzfxqh.modules.buildingKilometerGrid.model.vo.BuildingGridGetByIdVo;
import com.css.fxfzfxqh.modules.buildingKilometerGrid.model.vo.QueryByVersionVo;
import com.css.fxfzfxqh.modules.buildingKilometerGrid.model.vo.VersionParseFileVo;
import com.css.fxfzfxqh.modules.buildingKilometerGrid.repository.FxqhBuildingGridUrbanMasonryRepository;
import com.css.fxfzfxqh.modules.buildingKilometerGrid.strategy.ShpService;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.casualtiesDE.vo.Grid13VO;
import com.css.fxfzfxqh.util.EasyPoiExcelUtil;
import com.css.fxfzfxqh.util.ParsingResult;
import com.css.fxfzfxqh.util.ShpAnalyticUtil;
import com.css.fxfzfxqh.web.PlatformSessionContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 城镇砌体结构房屋格网
 */
@Service("czqtjggw")
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class FxqhBuildingGridUrbanMasonryService  implements ShpService {
    @Autowired
    FxqhBuildingGridUrbanMasonryRepository buildingGridUrbanMasonryRepository;
//    @Autowired
//    private RedisTemplate redisTemplate;
    ThreadLocal<Integer> shpIndex = ThreadLocal.withInitial(() -> 0); // shp文件解析下标
//    private static final String PARSE_CACHE = "fxqh:building_grid:urban_masonry:parse_cache:"; // 解析数据缓存 list
@Autowired
JcsjRestManager jcsjRestManager;

    @Override
    public VersionParseFileVo parseData(ParsingResult parsingResult, String tempVersionCode) throws ShpFieldException {
//        List<FxqhBuildingGridUrbanMasonry> list =
        if (parsingResult.getShpList() == null) {
            throw new ShpFieldException("文件内没有数据，请上传有数据的文件");
        }
        parseList(parsingResult.getShpList(), tempVersionCode);
//        buildingGridUrbanMasonryRepository.batchSave(list);
//        this.parseListSaveCache(list, dataVersion);
        VersionParseFileVo vo = new VersionParseFileVo();
        vo.setDataVersion(tempVersionCode);
        vo.setFieldNum(shpIndex.get());
        vo.setFieldEntry(parsingResult.getShpList().size());
        return vo;
    }

//    public static String getParseCacheKey(String key) {
//        return PARSE_CACHE + key;
//    }

//    /**
//     * 解析出的数据保存到缓存中 10分钟内不操作数据过期
//     *
//     * @param list
//     * @param key
//     */
//    private void parseListSaveCache(List<FxqhBuildingGridUrbanMasonry> list, String key) {
//        ListOperations<String, FxqhBuildingGridUrbanMasonry> ops = redisTemplate.opsForList();
//        ops.rightPushAll(getParseCacheKey(key), list);
//        redisTemplate.expire(getParseCacheKey(key), 10L, TimeUnit.MINUTES);
//    }

    @Override
    public void saveParseData(String sourceVersionCode, String targetVersionCode) throws BizException {
//        ListOperations<String, FxqhBuildingGridUrbanMasonry> ops = redisTemplate.opsForList();
//        List<FxqhBuildingGridUrbanMasonry> list = ops.range(getParseCacheKey(sourceVersionCode), 0, -1);
//        if (CollectionUtils.isEmpty(list)) {
//            throw new BizException("长时间未操作，数据已过期");
//        }
//        for (FxqhBuildingGridUrbanMasonry o : list) {
//            o.setDataVersion(targetVersionCode);
//        }
//        buildingGridUrbanMasonryRepository.batchSave(list);
//        redisTemplate.delete(getParseCacheKey(sourceVersionCode));
        buildingGridUrbanMasonryRepository.changeTempToRealData(sourceVersionCode, targetVersionCode);
    }

    @Override
    public QueryByVersionVo<FxqhBuildingGridUrbanMasonry> queryDataByVersionCode(QueryByVersionParam param) {
        List<FxqhBuildingGridUrbanMasonry> list = buildingGridUrbanMasonryRepository.listByDataVersion(param);
        Long total = buildingGridUrbanMasonryRepository.countByDataVersion(param);
        return QueryByVersionVo.build(list, param, total, FxqhBuildingGridTableTitleDesc.urban_masonry);
    }

    @Override
    public BuildingGridGetByIdVo<?> findById(String id) {
        FxqhBuildingGridUrbanMasonry obj = buildingGridUrbanMasonryRepository.getById(id);
        return BuildingGridGetByIdVo.build(obj, FxqhBuildingGridTableTitleDesc.urban_masonry);
    }

    @Override
    public void delByVersionCode(String versionCode, Date currTime, String currUid) {
        buildingGridUrbanMasonryRepository.delByVersionCode(versionCode, currTime, currUid);
    }

    private void parseList(List<List<Object>> shpList, String dataVersion) throws ShpFieldException {
        if (CollectionUtils.isEmpty(shpList)) {
            return;
        }
//        List<FxqhBuildingGridUrbanMasonry> fxqhBuildingGridUrbanMasonrys = new ArrayList<>();
        int index = 0;
        for (List<Object> list : shpList) {
            log.debug(list.toString());
            index = 0;
            FxqhBuildingGridUrbanMasonry fxqhBuildingGridUrbanMasonry = new FxqhBuildingGridUrbanMasonry();
            fxqhBuildingGridUrbanMasonry.setDataVersion(dataVersion);
            fxqhBuildingGridUrbanMasonry.setCreateUser(PlatformSessionContext.getUserID());
            fxqhBuildingGridUrbanMasonry.setCreateTime(new Date());
            fxqhBuildingGridUrbanMasonry.setDelFlag(YNEnum.N.toString());
            fxqhBuildingGridUrbanMasonry.setId(IdUtil.getSnowflakeNextIdStr());
            String geom = ShpAnalyticUtil.checkGeomTypeOf(list.get(index++), GeomTypeEnum.MULTIPOLYGON);
            if (StringUtils.isBlank(geom)) {
                continue;
            }
            fxqhBuildingGridUrbanMasonry.setGeom(geom);
            fxqhBuildingGridUrbanMasonry.setObjectid(ShpAnalyticUtil.getDoubleVal(list.get(index++), "OBJECTID", true));
            fxqhBuildingGridUrbanMasonry.setOid1(ShpAnalyticUtil.getDoubleVal(list.get(index++), "OID_1", true));
            fxqhBuildingGridUrbanMasonry.setGridRows(ShpAnalyticUtil.getDoubleVal(list.get(index++), "ROWS", true));
            fxqhBuildingGridUrbanMasonry.setColums(ShpAnalyticUtil.getDoubleVal(list.get(index++), "COLUMS", true));
            fxqhBuildingGridUrbanMasonry.setAreaCode(ShpAnalyticUtil.getStringVal(list.get(index++), "AREA_CODE", true));
            fxqhBuildingGridUrbanMasonry.setShapeLeng(ShpAnalyticUtil.getDoubleVal(list.get(index++), "SHAPE_LENG", true));
            fxqhBuildingGridUrbanMasonry.setShapeLe1(ShpAnalyticUtil.getDoubleVal(list.get(index++), "SHAPE_LE_1", true));
            fxqhBuildingGridUrbanMasonry.setShapeArea(ShpAnalyticUtil.getDoubleVal(list.get(index++), "SHAPE_AREA", true));
            fxqhBuildingGridUrbanMasonry.setTotalArea(ShpAnalyticUtil.getDoubleVal(list.get(index++), "总面积", true));
            fxqhBuildingGridUrbanMasonry.setHousecount(ShpAnalyticUtil.getIntegerVal(list.get(index++), "栋数", true));
            fxqhBuildingGridUrbanMasonry.setResidence(ShpAnalyticUtil.getDoubleVal(list.get(index++), "住宅房屋面积占比", true));
            fxqhBuildingGridUrbanMasonry.setOffice(ShpAnalyticUtil.getDoubleVal(list.get(index++), "办公房屋面积占比", true));
            fxqhBuildingGridUrbanMasonry.setBusiness(ShpAnalyticUtil.getDoubleVal(list.get(index++), "商业房屋面积占比", true));
            fxqhBuildingGridUrbanMasonry.setMedic(ShpAnalyticUtil.getDoubleVal(list.get(index++), "医疗教育面积占比", true));
            fxqhBuildingGridUrbanMasonry.setOther(ShpAnalyticUtil.getDoubleVal(list.get(index++), "其他房屋面积占比", true));
            fxqhBuildingGridUrbanMasonry.setY1980(ShpAnalyticUtil.getDoubleVal(list.get(index++), "1980年及以前房屋面积占比", true));
            fxqhBuildingGridUrbanMasonry.setY1981Y1990(ShpAnalyticUtil.getDoubleVal(list.get(index++), "1981_1990年房屋面积占比", true));
            fxqhBuildingGridUrbanMasonry.setY1991Y2000(ShpAnalyticUtil.getDoubleVal(list.get(index++), "1991-2000年房屋面积占比", true));
            fxqhBuildingGridUrbanMasonry.setY2001Y2010(ShpAnalyticUtil.getDoubleVal(list.get(index++), "2000-2010年房屋面积占比", true));
            fxqhBuildingGridUrbanMasonry.setY2011Y2015(ShpAnalyticUtil.getDoubleVal(list.get(index++), "2011-2015年房屋面积占比", true));
            fxqhBuildingGridUrbanMasonry.setY2016(ShpAnalyticUtil.getDoubleVal(list.get(index++), "2016及以后年房屋面积占比", true));
            fxqhBuildingGridUrbanMasonry.setF1(ShpAnalyticUtil.getDoubleVal(list.get(index++), "1层房屋面积占比", true));
            fxqhBuildingGridUrbanMasonry.setF2F3(ShpAnalyticUtil.getDoubleVal(list.get(index++), "2-3层房屋面积占比", true));
            fxqhBuildingGridUrbanMasonry.setF4F6(ShpAnalyticUtil.getDoubleVal(list.get(index++), "4-6层房屋面积占比", true));
            fxqhBuildingGridUrbanMasonry.setF7F10(ShpAnalyticUtil.getDoubleVal(list.get(index++), "7-10层房屋面积占比", true));
            fxqhBuildingGridUrbanMasonry.setF11F16(ShpAnalyticUtil.getDoubleVal(list.get(index++), "11-16层房屋面积占比", true));
            fxqhBuildingGridUrbanMasonry.setF17F30(ShpAnalyticUtil.getDoubleVal(list.get(index++), "17-30层房屋面积占比", true));
            fxqhBuildingGridUrbanMasonry.setF31(ShpAnalyticUtil.getDoubleVal(list.get(index++), "31层及以上房屋面积占比", true));
            fxqhBuildingGridUrbanMasonry.setOldLd0(ShpAnalyticUtil.getDoubleVal(list.get(index++), "原设防烈度_不设防房屋面积占比", true));
            fxqhBuildingGridUrbanMasonry.setOldLd1(ShpAnalyticUtil.getDoubleVal(list.get(index++), "原设防烈度_6度房屋面积占比", true));
            fxqhBuildingGridUrbanMasonry.setOldLd2(ShpAnalyticUtil.getDoubleVal(list.get(index++), "原设防烈度_7度房屋面积占比", true));
            fxqhBuildingGridUrbanMasonry.setOldLd3(ShpAnalyticUtil.getDoubleVal(list.get(index++), "原设防烈度_8度房屋面积占比", true));
            fxqhBuildingGridUrbanMasonry.setOldLd4(ShpAnalyticUtil.getDoubleVal(list.get(index++), "原设防烈度_9度房屋面积占比", true));
            fxqhBuildingGridUrbanMasonry.setNewLd0(ShpAnalyticUtil.getDoubleVal(list.get(index++), "现设防烈度_不设防房屋面积占比", true));
            fxqhBuildingGridUrbanMasonry.setNewLd1(ShpAnalyticUtil.getDoubleVal(list.get(index++), "现设防烈度_6度房屋面积占比", true));
            fxqhBuildingGridUrbanMasonry.setNewLd2(ShpAnalyticUtil.getDoubleVal(list.get(index++), "现设防烈度_7度房屋面积占比", true));
            fxqhBuildingGridUrbanMasonry.setNewLd3(ShpAnalyticUtil.getDoubleVal(list.get(index++), "现设防烈度_8度房屋面积占比", true));
            fxqhBuildingGridUrbanMasonry.setNewLd4(ShpAnalyticUtil.getDoubleVal(list.get(index++), "原设防烈度_9度房屋面积占比", true));
            fxqhBuildingGridUrbanMasonry.setReform(ShpAnalyticUtil.getDoubleVal(list.get(index++), "改造房屋面积占比", true));
            fxqhBuildingGridUrbanMasonry.setReinforce(ShpAnalyticUtil.getDoubleVal(list.get(index++), "加固房屋面积占比", true));

            fxqhBuildingGridUrbanMasonry.setProvince(ShpAnalyticUtil.getStringVal(list.get(index++), "省名称", false));
            fxqhBuildingGridUrbanMasonry.setProvinceCode(ShpAnalyticUtil.getStringVal(list.get(index++), "省CODE", false));
            fxqhBuildingGridUrbanMasonry.setCity(ShpAnalyticUtil.getStringVal(list.get(index++), "市名称", false));
            fxqhBuildingGridUrbanMasonry.setCityCode(ShpAnalyticUtil.getStringVal(list.get(index++), "市CODE", false));
            fxqhBuildingGridUrbanMasonry.setCounty(ShpAnalyticUtil.getStringVal(list.get(index++), "县名称", false));
            fxqhBuildingGridUrbanMasonry.setCountyCode(ShpAnalyticUtil.getStringVal(list.get(index++), "县CODE", false));
            fxqhBuildingGridUrbanMasonry.setKilometerGridId(ShpAnalyticUtil.getStringVal(list.get(index), "格网唯一ID", true));
            fxqhBuildingGridUrbanMasonry.setExtends1(ShpAnalyticUtil.getStringVal(list.get(index), "格网唯一ID", true));
            buildingGridUrbanMasonryRepository.insert(fxqhBuildingGridUrbanMasonry);
//            try {
//                GetChinaGridBo chinaGridIdNew = jcsjRestManager.getChinaGridIdNew(fxqhBuildingGridUrbanMasonry.getGeom(), fxqhBuildingGridUrbanMasonry.getProvince(), fxqhBuildingGridUrbanMasonry.getCity(), fxqhBuildingGridUrbanMasonry.getCounty());
//                if (chinaGridIdNew.getCode() == 200) {
//                    fxqhBuildingGridUrbanMasonry.setExtends1(chinaGridIdNew.getData());
//                }
//            } catch (Exception e) {
//                log.error(e.getMessage(), e);
//            }
//            fxqhBuildingGridUrbanMasonrys.add(fxqhBuildingGridUrbanMasonry);
        }
        shpIndex.set(index);
//        return fxqhBuildingGridUrbanMasonrys;
    }

    @Override
    public List<FxqhBuildingGridUrbanMasonry> listGridDataByVersionCode(String version) {
        return buildingGridUrbanMasonryRepository.listGridDataByVersionCode(version);
    }

    @Override
    public void dataExport(HttpServletResponse response, String versionCode) {
        List<FxqhBuildingGridUrbanMasonry> list = buildingGridUrbanMasonryRepository.listByDataVersion(QueryByVersionParam.builder().versionCode(versionCode).build());
        EasyPoiExcelUtil.exportExcel(list, "城镇砌体结构房屋格网汇总数据结构表", "sheet1", FxqhBuildingGridUrbanMasonry.class, "城镇砌体结构房屋格网汇总数据结构表", response);
    }

    @Override
    public List<Grid13VO> queryYwData(QueryByVersionParam queryByVersionParam) {
        return buildingGridUrbanMasonryRepository.queryYwData(queryByVersionParam);
    }

    @Override
    public List<Grid13VO> queryDataByParam(QueryByVersionParam param) {
        return buildingGridUrbanMasonryRepository.queryDataByParam(param);
    }
    @Override
    public List<Grid13VO> queryDataByParam1(QueryByVersionParam param) {
        return buildingGridUrbanMasonryRepository.queryDataByParam1(param);
    }
    @Override
    public List<Grid13VO> getJcld(QueryByVersionParam queryByVersionParam) {
        return buildingGridUrbanMasonryRepository.getJcld(queryByVersionParam);
    }

    @Override
    public List<Grid13VO> getPga(QueryByVersionParam queryByVersionParam) {
        return buildingGridUrbanMasonryRepository.getPga(queryByVersionParam);
    }

    @Override
    public void delDataById(String id) {
        buildingGridUrbanMasonryRepository.delDataById(id);
    }
}
